/**************************************************************************
 *
 *   Copyright 2010 American Public Media Group
 *
 *   This file is part of AIR2.
 *
 *   AIR2 is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   AIR2 is distributed in the hope that it will be useful, 
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License 
 *   along with AIR2.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/

Ext.ns('AIR2.Search.Source');

AIR2.Search.Source.ResponseWindow = function(args) {

    var url = AIR2.Search.URL + '.json?i=inquiries&q=' +
        Ext.urlEncode({inq_uuid:'('+args.inqUuids.join(' OR ')+')'});

    var cfg = {
        allowAdd: false,
        autoScroll: true,
        title: args.rec.get('title') + ' - ' + args.rec.get('primary_email'),
        defaults: { 
            border: false, 
            autoScroll: true, 
            frame: false, 
            style:'border:none',
            bodyStyle:'padding:15px'
        },
        items: {
            items: [ args.demographic, args.responses ]
        }
    };
    
    // if we already have Inquiry questions in local cache,
    // prefer those. Otherwise, fire off another XHR.
    if (args.needsXHR) {
    
        Ext.Ajax.request({
            url: url,
            success: function( resp, opts ) {
                //Logger(resp);
                var json = Ext.decode(resp.responseText);
                //Logger(cfg, json.total);
                //Logger(json);
                AIR2.Search.Inquiry.addToCache(json.results);
                AIR2.Search.Source.mergeQuestionsAndAnswers(args.responses);
                args.mask.hide();
                var win = new AIR2.UI.Window(cfg);
                win.show(args.button);
                //Logger("win.show()");
                
            },
            failure: function( resp, opts ) {
                Logger("Inquiry failure: ", resp);
                
            }
        });
    
    }
    else {
    
        AIR2.Search.Source.mergeQuestionsAndAnswers(args.responses);
        args.mask.hide();
        var win = new AIR2.UI.Window(cfg);
        win.show(args.button);
    
    }

}

AIR2.Search.Source.mergeQuestionsAndAnswers = function(responseSets) {
   
    Ext.each(responseSets, function(item,idx,array) {
        if (!Ext.isDefined(item) || !Ext.isDefined(item.inquiry)) {
            //throw new Ext.Error("no inquiry in " + item);
            Logger("no inquiry in " + item);
            return;
        }
        var inq = AIR2.Search.Inquiry.CACHE[item.inquiry.uuid];
        if (!inq) {
            //throw new Ext.Error("no inquiry for "+item.inquiry.uuid);
            Logger("no inquiry for "+item.inquiry.uuid);
            return;
        }
        item.inquiry.title = inq.title;
        item.title = inq.title + ' - ' + item.responseDate;
        var questions = inq.questions;
        Ext.each(item.items, function(resp,idx2,array2) {
            resp.html = '<div class="air2-search-qa">'+
                    '<div class="air2-search-question">'+
                    Ext.util.Format.htmlDecode(questions[resp.seq]).replace(/<br.*?>/gi, "")+
                    '</div>'+
                    '<div class="air2-search-answer">'+
                    resp.html+
                    '</div>'+
                    '</div>';
        });
    });
}

AIR2.Search.Source.getDemographicPanel = function(rec) {
    var p = new Ext.Panel({
        border: false,
        html: AIR2.Search.Source.makeDemographicHtml(rec)
    });
    return p;
}

AIR2.Search.Source.makeDemographicHtml = function(rec) {
    var fields = [
        'primary_email',
        'primary_location',
        'birth_year',
        'job_title',
        'employer',
        'user_gender',
        'user_ethnicity',
        'user_religion',
        'tag'
        
        
        // TODO more
    
    ];
    var demo = [];
    Ext.each(fields, function(item,idx,array) {
        var str = rec.json[item]; // not rec.get(item) because some fields (e.g. primary_location) are not in metaData
        if (Ext.isArray(str)) {
            str = str.join(', ');
        }
        demo.push({
            label: AIR2.Fixtures.FieldLabels[item]||item,
            f: item,
            v: str
        });
    });
    var tpl = new Ext.XTemplate(
      '<div class="air2-source-demographic">',
       '<table>',
        '<tpl for=".">',
          '<tr class="{[xindex % 2 ? "alt" : ""]}"><th>{label}</th><td>{v}</td></tr>',
        '</tpl>',
       '</table>',
      '</div>'
    );
    return tpl.apply(demo);
}

AIR2.Search.Source.getResponsesPanel = function(rec) {
    var qas = rec.json.qa; // not a defined field
    var resp = [];
    Ext.each(qas, function(item,idx,array) {
        var m = item.match(/^(.+?):(\w+):(\d+):(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d):(.+)/);
        //Logger(m);
        resp.push(new Ext.Panel({
            inqUuid     :m[2],
            responseDate:m[4],
            seq         :parseInt(m[3]), 
            answer      :m[5], 
            border      :false,
            html        :m[5]  // TODO a tpl 
        }));

    });
    
    //sort by inquiry asc, then by sequence asc
    var sorter = function(a,b) {
        if (a.inqUuid > b.inqUuid) { return 1  }
        if (a.inqUuid < b.inqUuid) { return -1 }
        if (a.seq > b.seq) { return 1  }
        if (a.seq < b.seq) { return -1 }
        return 0;
    }
    resp.sort(sorter);

    // now group into response sets
    var RS = {};
    Ext.each(resp, function(item,idx,array) {
        var key = item.inqUuid + item.responseDate;
        if (!Ext.isDefined(RS[key])) {
            RS[key] = {
                items: [],
                cls: 'air2-response-set',
                iconCls: 'air2-icon-responses',
                responseDate: item.responseDate,
                inquiry: { uuid: item.inqUuid },
                collapsible: true,
                border: false,
                frame: false
            };
        }
        RS[key].items.push(item);
    });

    var RSArr = [];
    Ext.iterate(RS, function(uuid,inqPanel,panels) {
        RSArr.push(inqPanel);
    });
    // sort response sets by date desc
    var RSsorter = function(a,b) {
        if (a.responseDate < b.responseDate) { return 1 }
        if (a.responseDate > b.responseDate) { return -1 }
        return 0;
    }
    RSArr.sort(RSsorter);
    //Logger("response sets:", RSArr);
    return RSArr;

}

AIR2.Search.Source.Details = function(button, rank) {
    var mask = new Ext.LoadMask(Ext.getBody(), {msg:'One moment please...'});
    mask.show();
    var recIdx = rank - AIR2.Search.DATAVIEW.baseRankNum + 1;
    //Logger("rank=",rank,"recIdx=",recIdx);
    var rec = AIR2.Search.DATAVIEW.getStore().getAt(recIdx);
    //Logger("rec=", rec);
    var demographic = AIR2.Search.Source.getDemographicPanel(rec);
    var responseSets = AIR2.Search.Source.getResponsesPanel(rec);
    var inqUuids = [];
    var needsXHR = false;
    Ext.each(responseSets, function(item,idx,array) {
        if (!Ext.isDefined(AIR2.Search.Inquiry.CACHE[item.inquiry.uuid])) {
            needsXHR = true;
        }
        inqUuids.push(item.inquiry.uuid);
    });
    AIR2.Search.Source.ResponseWindow({
        rec         : rec,
        inqUuids    : inqUuids,
        demographic : demographic,
        button      : button,
        responses   : responseSets,
        needsXHR    : needsXHR,
        mask        : mask
    });
    
}
